//
//  HTLineMapVC.m
//  TruckDriver
//
//  Created by Ting Han on 2017/10/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTLineMapVC.h"
//高德地图
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import <MapKit/MapKit.h>

#import "CommonUtility.h"
#import "MANaviRoute.h"

@interface HTLineMapVC ()<AMapSearchDelegate,MAMapViewDelegate>

@property (weak, nonatomic) IBOutlet MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UIImageView *firstImageView;
@property (weak, nonatomic) IBOutlet UILabel *firstLabel;
@property (weak, nonatomic) IBOutlet UILabel *firstDetialLabel;
@property (weak, nonatomic) IBOutlet UIImageView *secondImageView;
@property (weak, nonatomic) IBOutlet UILabel *secondLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondDetialLabel;
@property (weak, nonatomic) IBOutlet UIImageView *thirdImageView;
@property (weak, nonatomic) IBOutlet UILabel *thirdLabel;
@property (weak, nonatomic) IBOutlet UILabel *thirdDetialLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (weak, nonatomic) IBOutlet UIButton *ConformButton;

@property (nonatomic,assign) NSInteger index;
//路径规划
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic,strong) NSMutableArray *routes;


/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;

@property (nonatomic, strong) CLGeocoder *geoC;

@end

@implementation HTLineMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地图路线";
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    self.index = 0;
    [self selectedIndex:self.index];
    [self configGesture];
    [self configMap];
}
- (void)configMap{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    self.mapView.showsCompass = NO;
    self.routes = [NSMutableArray array];
    _geoC = [[CLGeocoder alloc] init];
   
    [self.geoC geocodeAddressString:self.detialModel.startname completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        if(error == nil)
        {
            self.startCoordinate = pl.location.coordinate;
            [self.geoC geocodeAddressString:self.detialModel.endname completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                CLPlacemark *pl = [placemarks firstObject];
                
                if(error == nil)
                {
                    self.destinationCoordinate = pl.location.coordinate;
                    [self addDefaultAnnotations];
                    [self searchRoutePlanningDriveWithStrategy:2];
                    [self searchRoutePlanningDriveWithStrategy:1];
                    [self searchRoutePlanningDriveWithStrategy:0];
                }
            }];
        }
    }];
}
- (void)searchRoutePlanningDriveWithStrategy:(NSInteger)strategy
{
    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    navi.strategy = strategy;
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapDrivingRouteSearch:navi];
}

- (void)didTapGesture:(UITapGestureRecognizer *)tap{
    if (self.routes == nil || self.routes.count != 3) {
        return;
    }
    switch (tap.view.tag) {
        case 161:
        {
            if (self.index == 0) {
                return;
            }
            self.index = 0;
            [self selectedIndex:self.index];
            [self clear];
            [self presentCurrentCourse];
        }
            break;
        case 162:
        {
            if (self.index == 1) {
                return;
            }
            self.index = 1;
            [self selectedIndex:self.index];
            [self clear];
            [self presentCurrentCourse];
        }
            break;
        case 163:
        {
            if (self.index == 2) {
                return;
            }
            self.index = 2;
            [self selectedIndex:self.index];
            [self clear];
            [self presentCurrentCourse];
        }
            break;
            
        default:
            break;
    }
}
//开始导航
- (IBAction)startNarvi:(id)sender {
    [self showAlertControllerNavStart:self.startCoordinate end:self.destinationCoordinate];
}
#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 5;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.image = nil;
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }
        else
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:@"起始点"])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"startPoint"];
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:@"终点"])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"endPoint"];
            }
            
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    DBLog(@"Error: %@", error);
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    if (response.count > 0)
    {
        [self.routes addObject:response.route.paths[0]];
        if (self.routes.count == 3) {
            [self presentCurrentCourse];
            [self setupBottomViewTitle];
        }
    }
}

#pragma mark -- 工具
- (void)configGesture{
    self.ConformButton.backgroundColor = kBlueColor;
    self.firstImageView.userInteractionEnabled = YES;
    self.secondImageView.userInteractionEnabled = YES;
    self.thirdImageView.userInteractionEnabled = YES;
    self.firstImageView.tag = 161;
    self.secondImageView.tag = 162;
    self.thirdImageView.tag = 163;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.firstImageView addGestureRecognizer:tap];
    [self.secondImageView addGestureRecognizer:tap1];
    [self.thirdImageView addGestureRecognizer:tap2];
    
}
- (void)selectedIndex:(NSInteger)index{
    if (index == 0) {
        [self selectedBottomView:YES imageView:self.firstImageView label:self.firstLabel detailLabel:self.firstDetialLabel];
        [self selectedBottomView:NO imageView:self.secondImageView label:self.secondLabel detailLabel:self.secondDetialLabel];
        [self selectedBottomView:NO imageView:self.thirdImageView label:self.thirdLabel detailLabel:self.thirdDetialLabel];
    }
    if (index == 1) {
        [self selectedBottomView:NO imageView:self.firstImageView label:self.firstLabel detailLabel:self.firstDetialLabel];
        [self selectedBottomView:YES imageView:self.secondImageView label:self.secondLabel detailLabel:self.secondDetialLabel];
        [self selectedBottomView:NO imageView:self.thirdImageView label:self.thirdLabel detailLabel:self.thirdDetialLabel];
    }
    if (index == 2) {
        [self selectedBottomView:NO imageView:self.firstImageView label:self.firstLabel detailLabel:self.firstDetialLabel];
        [self selectedBottomView:NO imageView:self.secondImageView label:self.secondLabel detailLabel:self.secondDetialLabel];
        [self selectedBottomView:YES imageView:self.thirdImageView label:self.thirdLabel detailLabel:self.thirdDetialLabel];
    }
    
}
- (void)selectedBottomView:(BOOL)isSelected imageView:(UIImageView *)imageView label:(UILabel *)label detailLabel:(UILabel *)detialLabel{
    if (isSelected) {
        imageView.backgroundColor = kBlueColor;
        label.textColor = [UIColor whiteColor];
        detialLabel.textColor = [UIColor whiteColor];
    }else{
        imageView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        label.textColor = [UIColor darkGrayColor];
        detialLabel.textColor = [UIColor blackColor];
    }
}
- (void)addDefaultAnnotations
{
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = @"起始点";
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      = @"终点";
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    [self.mapView addAnnotation:startAnnotation];
    [self.mapView addAnnotation:destinationAnnotation];
}
/* 展示当前路线方案. */
- (void)presentCurrentCourse
{
    if (self.routes == nil || self.routes.count <= 0) {
        return;
    }
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    self.naviRoute = [MANaviRoute naviRouteForPath:self.routes[self.index] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.startAnnotation.coordinate.latitude longitude:self.startAnnotation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destinationAnnotation.coordinate.latitude longitude:self.destinationAnnotation.coordinate.longitude]];
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                        edgePadding:UIEdgeInsetsMake(0, 0, 0, 0)
                           animated:YES];
}

/* 清空地图上已有的路线. */
- (void)clear
{
   
    [self.naviRoute removeFromMapView];
}
- (void)setupBottomViewTitle{
    for (int i = 0; i < self.routes.count; i++) {
        AMapPath *path = self.routes[i];
        if (i == 0) {
            self.firstLabel.text = path.strategy;
            self.firstDetialLabel.text = [NSString stringWithFormat:@"约%ld公里",path.distance/1000];
        }
        if (i == 1) {
            self.secondLabel.text = path.strategy;
            self.secondDetialLabel.text = [NSString stringWithFormat:@"约%ld公里",path.distance/1000];
        }
        if (i == 2) {
            self.thirdLabel.text =  path.strategy;
            self.thirdDetialLabel.text = [NSString stringWithFormat:@"约%ld公里",path.distance/1000];
        }
    }
    
}

#pragma mark --- 导航
- (void)showAlertControllerNavStart:(CLLocationCoordinate2D )startCoordinate end:(CLLocationCoordinate2D )endCoordinate{
   
    if (!([UIDevice currentDevice].systemVersion.doubleValue >= 8.0)) {
        return;
    }
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"导航到设备" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //自带地图
    [alertController addAction:[UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //使用自带地图导航
        MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
        currentLocation.name = @"我的位置";
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoordinate addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
        
    }]];
    
    //判断是否安装了高德地图，如果安装了高德地图，则使用高德地图导航
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        [alertController addAction:[UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&poiname=%@&lat=%f&lon=%f&dev=0&style=2",@"qvBus",@"", endCoordinate.latitude,endCoordinate.longitude ] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlString]];
            
        }]];
    }
    
    //判断是否安装了百度地图，如果安装了百度地图，则使用百度地图导航
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        [alertController addAction:[UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02",endCoordinate.latitude,endCoordinate.longitude,@""] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
            
        }]];
    }
    //添加取消选项
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [alertController dismissViewControllerAnimated:YES completion:nil];
        
    }]];
    //显示alertController
    [self presentViewController:alertController animated:YES completion:nil];
    
}

@end
